package com.ccpdown.util.show;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class BitmapDownloader {

	public static ImageView iv;
	static Bitmap bitmap;

	/*
	 * 图片设置BITMAP
	 * 
	 * @imgView 设置该ImageView
	 * 
	 * @path 设置远程图片的路径；
	 * 
	 * @drawable 当图片不存在或错误时显示的默认图片
	 */
	public static void setSocketImg(ImageView imgView, String path,
			Drawable drawable) {
		iv = imgView;
		iv.setImageDrawable(drawable);
		if (path != null && (!path.equals(""))) {
			LoadThread lt = new LoadThread(path);
			new Thread(lt).start();
		}
	}
}

class LoadThread implements Runnable {

	private String path;

	private int responseCode;

	private Handler imgHandler = new Handler() {
		public void handleMessage(Message msg) {
			BitmapDownloader.iv.setImageBitmap(BitmapDownloader.bitmap);
			super.handleMessage(msg);
		}
	};

	public LoadThread(String path) {
		this.path = path;
	}

	public int getResponseCode() {
		return responseCode;
	}

	public boolean getUrlBitmap() {
		URL url = null;
		InputStream is = null;
		boolean flag = false;
		try {
			url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			is = conn.getInputStream();
			responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				BitmapDownloader.bitmap = BitmapFactory.decodeStream(is);
				flag = true;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return flag;
	}

	@Override
	public void run() {
		if (getUrlBitmap()) {
			imgHandler.sendEmptyMessage(0);
		}
	}
}
